package program;

import java.text.Collator;
import java.util.Arrays;
import java.util.Locale;

import kernel.FileManager;
import kernel.exception.OSException;
import kernel.process.AbstractProcess;
import kernel.process.AbstractProcessHeader;

/**
 * Sort process.
 * For more see man() method.
 * @author Petr Hajek, Veronika Vencurikova
 *
 */
public class Sort extends AbstractProcess {

	public Sort(AbstractProcessHeader header, long pid) {
		super(header, pid);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String doJob(String input) throws OSException {
		if (this.params.size() > 1) throw new OSException(OSException.ERR_MANY_ARGS);
		else if (this.params.size() == 1) input = FileManager.readData(absPath(this.params.get(0), shellID));
		
		String[] parsedIn = input.split("\n");
		Collator c = Collator.getInstance(new Locale("cs"));
		Arrays.sort(parsedIn,c);
		String out = "";
		for (int i = 0; i < parsedIn.length; i++) {
			out += parsedIn[i] + "\n";
		}
		return out;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean needParams() {
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void kill() throws OSException {

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String continueJob() throws OSException {
		this.shouldEnd = true;
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected String finalizeJob() throws OSException {
		return null;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String man(String command) {
	String man = "";
		
		man += "    sorts lines of text files alfabetically\n";
		man += "\n";
		man += "Command syntax:\n";
		man += "    sort\n";
		
		return man;
	}

}
